import React, {useState} from 'react';
import {DatePicker} from 'antd';
import moment from 'moment';

const {RangePicker} = DatePicker;

const Index = props => {
    const {
        value,
        onChange,
        onCalendarChange,
        dayRange,
        disabledDate: outDisabledDate,
        ...rest
    } = props;

    const [dates, setDates] = useState([]);
    const [hackValue, sethackValue] = useState();
    const [innerValue, setinnerValue] = useState(value);
    const disabledDate = current => {
        let outDisable = false;
        if (typeof outDisabledDate === 'function') {
            outDisable = outDisabledDate(current);
        }

        let tooLate = false;
        let tooEarly = false;
        if (dates?.length > 0 && dayRange > 0) {
            tooLate = dates[0] && current.diff(dates[0], 'days') > dayRange;
            tooEarly = dates[1] && dates[1].diff(current, 'days') > dayRange;
        }

        return tooEarly || tooLate || outDisable;
    };

    const onOpenChange = open => {
        if (open) {
            sethackValue([]);
            setDates([]);
        } else {
            sethackValue(void 0);
        }
    };

    const handleCalenderChange = val => {
        setDates(val);
        typeof onCalendarChange === 'function' && onCalendarChange(val);
    };

    const handleChange = val => {
        setinnerValue(val);
        typeof onChange === 'function' && onChange(val);
    };

    return (
        <RangePicker
            {...rest}
            value={hackValue || innerValue}
            disabledDate={disabledDate}
            onCalendarChange={handleCalenderChange}
            onChange={handleChange}
            onOpenChange={onOpenChange}
        />
    );
};

export default Index;
